package com.entitymapper.xml.rfid;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

public class Configure {
	
	private static Map<String,Map<String,List<String>>> configureMap = new HashMap<String, Map<String,List<String>>>();
	private String configureFile = "rfid.main.xml";
	
	public Configure() {
	}
	
	public Configure(String configureFile) {
		this.configureFile = configureFile;
	}
	
	public void configure() {
		String path = this.getClass().getClassLoader().getResource("").getPath();
		String configureFilePath = path + configureFile;
		//System.out.println("file path : "+configureFilePath);
		File configureFile = new File(configureFilePath);
		
		SAXReader saxReader = new SAXReader();
		try {
			Document mainDocument = saxReader.read(configureFile);
			Element mainElement = mainDocument.getRootElement();
			for(Iterator<?> iter = mainElement.elementIterator(); iter.hasNext(); ) {
				Element rootName = (Element) iter.next();
				this.parserXmlFile(saxReader, new File(path+rootName.attributeValue("resource")));
			}
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	private void parserXmlFile(SAXReader saxReader,File file) {
		try {
			Document mainDocument = saxReader.read(file);
			Element mainElement = mainDocument.getRootElement();
			Map<String,List<String>> map = new HashMap<String, List<String>>();
			
			String entityName = null;
			for(Iterator<?> iter = mainElement.elementIterator(); iter.hasNext(); ) {
				Element rootName = (Element) iter.next();
				entityName = rootName.attributeValue("id");
				for(Iterator<?> atrIter = rootName.elementIterator(); atrIter.hasNext();) {
					List<String> valueList = new ArrayList<String>();
					Element atrName = (Element) atrIter.next();
					valueList.add(atrName.attributeValue("areaCount"));
					valueList.add(atrName.attributeValue("areaStarts"));
					valueList.add(atrName.attributeValue("updateStatus"));
					map.put(atrName.attributeValue("name"), valueList);
				} 
			}
			configureMap.put(entityName, map);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
	
	public static Map<String, Map<String,List<String>>> getConfigureMap() {
		return configureMap;
	}
}
